﻿using Learn.Infraestrutura.Attr;
using Learn.Infraestrutura.Dto.Response;
using Learn.Infraestrutura.EFCore;
using Learn.Service.Instance;
using Learn.Service.Interface;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.IO;
using System.Text;
using System;
using System.Reflection;
using Learn.Infraestrutura.Tools;

namespace Learning.Api.Admin.Filters
{
    public class Action_Log_Filter : ActionFilterAttribute
    {
        private readonly I_Log_Service _log_Service;

        public Action_Log_Filter(I_Log_Service log_Service)
        {
            _log_Service = log_Service;

        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            var result = ((ObjectResult)context.Result)?.Value;
            if (result == null)
                return;

            var api_result = result as Api_Result;
            if (api_result == null)
                return;

            var action = context.ActionDescriptor as ControllerActionDescriptor;
            var attr = action.MethodInfo.GetCustomAttribute<Action_Log_Attribute>();
            if (attr == null)
                return;//无需记录

            var name = attr.name;
            var type = attr.type;
            var version = attr.version;

            //获取请求参数
            string paras = "";
            if (context.HttpContext.Request.Method.ToUpper() == "GET")
            {
                var keys = context.HttpContext.Request.Query.Keys;
                foreach (var item in keys)
                {
                    paras += $"{item}={context.HttpContext.Request.Query[item]};";
                }
            }
            else
            {
                var request = context.HttpContext.Request;
                request.EnableBuffering();
                if (request.Method.ToLower().Equals("post"))
                {
                    request.Body.Seek(0, SeekOrigin.Begin);
                    using var reader = new StreamReader(request.Body, Encoding.UTF8);
                    paras = reader.ReadToEnd();
                }
            }

            SysActionLogs sysActionLogs = new SysActionLogs()
            {
                Alid = Config.GUID(),
                Alaction = name,
                AlapiUrl = context.HttpContext.Request.Path,//当前请求的接口地址
                AlcreateTime = DateTime.Now,
                Aldesc = "",
                Alip = Config.GetIp(),
                Alparams = paras,
                Alresult = (int)api_result.code,
                AlresultMessage = api_result.message,
                Altype = type,
                Aluid = "",//用户信息 隐藏在headers 里面的authorization 
                Alversion = version,
            };
            _log_Service.Add_Action_Log(sysActionLogs);
            //重置返回值 data=null 就移除data属性
            context.Result = SetResult(api_result);
        }

        /// <summary>
        /// 重置返回值
        /// </summary>
        /// <param name="result"></param>
        private IActionResult SetResult(Api_Result result)
        {
            object okResult;
            if (result.data == null)
            {
                okResult = new
                {
                    result.code,
                    result.message
                };
            }
            else
            {
                // var data = JsEncryptHelper.RSAEncrypt(JsonConvert.SerializeObject(result.data));
                okResult = new
                {
                    result.code,
                    result.message,
                    result.data
                };
            }
            return new OkObjectResult(okResult);

        }


    }
}

